<template>
  <div class="mail-edit">
    <div class="mail-edit-value">
      <div v-html="detailHtml" v-hijackJump @click="imgDomPreview"></div>
      <MailAttachmentListPreview :email-attachment-list="emailAttachmentPreviewList" />
    </div>

    <div class="mail-edit-wrap">
      <div class="recipientList">
        <OperatorTags :label="i18n.t('common.base.addressee')" :dynamic-tags="sendForm.receiver" />
      </div>
      <div class="copyList">
        <OperatorTags :label="i18n.t('performance.label.carbonCopy')" :dynamic-tags="sendForm.cc" />
      </div>
      <div class="subject">
        <span class="label">{{ i18n.t('event.detail.components.dialog.text8') }}</span>
        <el-input v-model="sendForm.subject"></el-input>
      </div>

      <div class="edit">
        <!-- 工具栏 -->
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
        <!-- 编辑器 -->
        <Editor class="w-edit" :defaultConfig="editorConfig" :defaultContent="jsonContent" v-model="sendForm.content" @onCreated="onCreated" @onChange="onChange" />
      </div>
      <div class="bottom">
        <div class="file">
          <button type="button" class="base-comment-tool file-button" @click="chooseFile"><i class="iconfont icon-attachment"></i></button>
          <div class="base-comment-attachment base-file__preview file-item" v-if="sendForm.emailAttachmentList.length > 0">
            <base-file-item formEditingMode="create" v-for="file in sendForm.emailAttachmentList" :source="sendForm.emailAttachmentList" :key="file.id" :file="file" @delete="deleteFile" size="small"></base-file-item>
          </div>
          <input style="display: none" type="file" ref="uploadInput" @change="handleChange" multiple />
        </div>
        <div class="buttons">
          <el-button @click="closeMailEdit">{{ i18n.t('common.base.cancel') }}</el-button>
          <el-button type="primary" @click="send" :loading="sendLoading">{{ i18n.t('common.base.send') }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
/** vue */
import { defineComponent, reactive, toRefs, onBeforeUnmount, ref, computed } from 'vue';
import EventBus from '@src/util/eventBus';
/** components */
import OperatorTags from '@src/modules/im/components/OperatorTags.vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { i18nChangeLanguage } from '@wangeditor/editor';
import MailAttachmentListPreview from '@src/modules/im/components/MailAttachmentListPreview.vue';
/** util */
import { uploadFile } from '@src/modules/im/imChat/components/messageBox/inputEdit/util.js';
import i18n from '@src/locales';
import Uploader from '@src/util/uploader';
import { customerServiceSendNewMessage } from '@src/modules/im/imChat/components/messageBox/send.js';
import { renderReceiver, renderSender, imgDomPreview } from '@src/modules/im/imChat/utils/tools.js';
import { formatDate } from 'pub-bbx-utils';
import { cloneDeep, difference } from 'lodash';
import { deleteServerFiles } from 'pub-bbx-utils';

/** element-ui */
import { Message, Loading, MessageBox } from 'element-ui';
/** directives */
import { hijackJump } from '@src/modules/im/tools/directives.js';

let laEnv = i18n.locale;
if (laEnv !== 'zh') {
  i18nChangeLanguage('en');
}

export default defineComponent({
  name: 'MailEdit',
  emits: ['toggleMailEdit'],
  directives: {
    hijackJump,
  },
  components: {
    OperatorTags,
    Editor,
    Toolbar,
    MailAttachmentListPreview,
  },
  setup(props, { emit }) {
    const uploadInput = ref();

    const emailAttachmentPreviewList = computed(() => {
      return state?.messageData?.messageContent?.customExts?.emailAttachmentList ?? [];
    });

    const state = reactive({
      messageData: {},
      sendType: '', // 1:回复 2全部回复 3转发
      detailHtml: '',
      show: true,
      sendLoading: false,
      sendForm: {
        receiver: [],
        cc: [],
        subject: '',
        messageId: '',
        emailAttachmentList: [],
        content: '',
      },
      editor: null,
      jsonContent: [
        {
          type: 'paragraph',
          lineHeight: '1',
          children: [{ text: '', fontFamily: '微软雅黑', fontSize: '14px' }],
        },
      ],
      toolbarConfig: {
        excludeKeys: ['code', 'codeBlock', 'blockquote', 'group-video', 'headerSelect', 'fontSize', 'fontFamily', 'bulletedList', 'numberedList', 'todo', 'lineHeight', 'divider', 'insertLink', 'insertTable', 'undo', 'redo'],
      },
      editorConfig: {
        placeholder: i18n.t('im.imChat.components.messageBox.inputEdit.pla1'),
        MENU_CONF: {
          uploadImage: {
            async customUpload(file, insert) {
              try {
                const data = await uploadFile(file);
                insert(data.ossUrl,data.id); // insertFn(url, alt, href)
              } catch (error) {
                console.error('catch', error);
                Message.error(error);
              }
            },
          },
        },
        hoverbarKeys: {
          image: {
            menuKeys: ['imageWidth30', 'imageWidth50', 'imageWidth100', 'editImage', 'deleteImage'],
          },
        },
      },
      oldContent: {
        oldImages: [],
      }
    });

    function init(data = {}) {
      state.messageData = data;
      state.detailHtml = data?.messageContent?.customExts?.content ?? '';
      state.sendForm.messageId = data?.messageContent?.customExts?.messageId;
      state.sendForm.subject = `${i18n.t('common.base.reply')}：${data?.messageContent?.customExts?.subject ?? ''}`;
      data?.messageContent?.customExts?.sender && state.sendForm.receiver.push(data?.messageContent?.customExts?.sender);
    }

    // 编辑器 - s
    function onCreated(editor) {
      state.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
    }

    function destroyEdit() {
      const editor = state.editor;
      if (editor == null) return;
      editor.destroy(); // 组件销毁时，及时销毁 editor ，重要！！！
    }

    // 编辑器 - e

    async function send() {
      try {
        // 判断收件人收件人不能为空，收件人发件人选了一个就行
        if (state.sendForm.receiver.length == 0 && state.sendForm.cc.length == 0) return Message.warning(i18n.t('im.imChat.components.mailChat.text12'));

        // 判断主题和回复内容是否为空
        const haveSubject = state.sendForm.subject;
        if (!haveSubject) await MessageBox.confirm(i18n.t('im.imChat.components.mailChat.text6'), i18n.t('common.base.toast'));

        const haveContent = !state.editor.isEmpty();
        if (!haveContent) await MessageBox.confirm(i18n.t('im.imChat.components.mailChat.text7'), i18n.t('common.base.toast'));

        state.sendLoading = true;

        const params = {
          conversationId: state.messageData.conversationId,
          messageType: 'email',
          messageContent: {
            customEvent: 'email',
            customExts: cloneDeep(state.sendForm),
            type: 'custom',
          },
        };
        // 发送内容追加原邮件内容
        params.messageContent.customExts.content += addOriginalEmail(state.messageData);

        const messageInfo = await customerServiceSendNewMessage(params);
        Message.success(i18n.t('im.imChat.components.mailChat.text8'));
        EventBus.$emit('addMessageByKF', messageInfo);
        closeMailEdit();
      } catch (error) {
        console.error('catch', error);
      } finally {
        state.sendLoading = false;
      }
    }
    // 删除附件
    function deleteFile(file) {
      let index = state.sendForm.emailAttachmentList.indexOf(file);
      if (index >= 0) {
        state.sendForm.emailAttachmentList.splice(index, 1);
      }
    }
    // 上传附件
    function handleChange(event) {
      const files = event.target.files;
      let loadingInstance = Loading.service({ fullscreen: true });
      Uploader.batchUploadWithParse({ files })
        .then(result => {
          let { success, error } = result;
          if (error.length > 0) {
            let message = error.map(item => item.message).join('\n');
            Message.error(message);
          }
          if (success.length > 0) {
            state.sendForm.emailAttachmentList = state.sendForm.emailAttachmentList.concat(success);
          }
        })
        .catch(err => console.error(err))
        .finally(() => {
          loadingInstance.close();
        });
    }

    function chooseFile() {
      uploadInput.value.value = null;
      uploadInput.value.click();
    }

    function closeMailEdit() {
      emit('toggleMailEdit', false);
    }

    function addOriginalEmail(messageData) {
      const customExts = messageData?.messageContent?.customExts ?? {};
      const newValue = `<blockquote>------------------------------------------------------------------<br>${i18n.t('event.detail.components.dialog.text4')}：${renderSender({ senderName: customExts.senderName, sender: customExts.sender })}<br>${i18n.t('common.base.sendTime')}：${formatDate(messageData.createTime)}<br>${i18n.t('common.base.addressee')}：${renderReceiver(customExts.receiver)}<br>${i18n.t('event.detail.components.dialog.text8')}：${customExts.subject}<br><br>${customExts.content}<br><br><br><br><br><br></blockquote>`;
      return newValue;
    }

    function dangerouslyInsertHtml(value) {
      state.editor.focus();
      state.editor.dangerouslyInsertHtml(value);
    }

    // 比较内容
    function diffContent() {
      try {
        const { oldImages } = state.oldContent
        const images = state.editor.getElemsByType('image')
        // 比较图片，判断是否有被删除
        {
          const diffImagesIds = difference(oldImages.map(v=>v.alt), images.map(v=>v.alt))
          if (diffImagesIds.length) {
            deleteServerFiles(diffImagesIds)
          }
        }
        
        // 更新旧值
        state.oldContent = {
          oldImages: images
        }
      } catch (error) {
        console.log(error)
      }
    }

    function onChange() {
      diffContent()
    }

    onBeforeUnmount(() => {
      destroyEdit();
    });

    return {
      uploadInput,
      ...toRefs(state),
      init,
      onCreated,
      destroyEdit,
      send,
      deleteFile,
      handleChange,
      chooseFile,
      closeMailEdit,
      addOriginalEmail,
      emailAttachmentPreviewList,
      imgDomPreview,
      dangerouslyInsertHtml,
      i18n,
      onChange,
    };
  },
});
</script>
<style lang="scss" scoped>
.mail-edit {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background-color: #ffffff;
  box-sizing: border-box;
  padding: 16px 16px 10px;
  display: flex;
  flex-direction: column;
  z-index: 999;
  &-value {
    min-height: 100px;
    max-height: 40%;
    overflow-y: auto;
    word-wrap: break-word;
    ::v-deep p {
      margin: 5px 0 !important;
    }
  }
  &-wrap {
    height: 0;
    flex: 1;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    .recipientList,
    .copyList {
      border-bottom: 1px solid #e4e7ed;
      max-height: 80px;
      overflow-y: auto;
    }
    .subject {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 33px;
      border-bottom: 1px solid #e4e7ed;
      padding: 0px 12px;
      .label {
        flex-shrink: 0;
        margin-right: 20px;
        font-size: 12px;
      }
      ::v-deep .el-input__inner {
        border: none;
      }
    }
    .edit {
      height: 0;
      flex: 1;
      display: flex;
      flex-direction: column;
      .w-edit {
        height: 0;
        flex: 1;
        // padding: 5px 10px;
        box-sizing: border-box;
        ::v-deep .w-e-text-container [data-slate-editor] {
          min-height: 95% !important; // 解决默认会显示滚动条的问题
        }
        ::v-deep .w-e-text-placeholder {
          font-style: inherit !important;
        }
      }
    }
    ::v-deep .w-e-full-screen-container {
      z-index: 99999 !important;
    }
    ::v-deep .w-e-bar-item {
      padding: 0 !important;
    }
    ::v-deep .w-e-menu-tooltip-v5 svg {
      width: 12px !important;
      height: 12px !important;
    }
    ::v-deep .w-e-bar-divider {
      display: none !important;
    }

    ::v-deep .w-e-text-placeholder {
      top: 10px !important;
    }

    ::v-deep .w-e-text-container [data-slate-editor] p {
      margin: 5px 0 !important;
    }

    .bottom {
      position: relative;
      display: flex;
      padding: 12px;
      justify-content: space-between;
      border-top: 1px solid #e4e7ed;
      flex-shrink: 0;
      max-height: 100px;
      overflow-y: auto;
      .file {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        .base-comment-attachment {
          padding: 2px 8px;
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          ::v-deep .base-file-item {
            flex-shrink: 0;
          }
        }
        .file-button {
          position: sticky;
          left: 0;
          top: 4px;
          margin-right: 10px;
        }
      }
      .buttons {
        position: sticky;
        top: 0;
        right: 0;
        flex-shrink: 0;
        margin-left: 10px;
      }
    }
  }
}
</style>
